import 'dart:isolate';

///isolate 通信 - 非阻塞式 NIO
void main() {
  print("main begin");

  ReceivePort receivePort = ReceivePort();

  SendPort? childSendPort = null;

  Isolate.spawn(newThread,["你好",receivePort.sendPort]);
  //方案1：通过listen进行监听
  receivePort.listen((message) {
    if(message is SendPort){
      childSendPort = message;
    }else{
      print("listen方式-主线程接收到消息：$message");
      childSendPort?.send("主线程发送给子线程的消息");
    }
  });

  print("main end");
}


///参数的定义可以随意，参数中接收的SendPort是需要通信的发送端口
///@sendPort
void newThread(var message){
  
  ReceivePort receivePort = ReceivePort();
  
  String msg = message[0];
  SendPort sendPort = message[1];
  print("通过参数传递的数据1：$msg");
  sendPort.send(receivePort.sendPort);
  //通过传递过来的sendPort给主线程回消息
  sendPort.send("这个是子线程给主线程回的消息！！！");

  receivePort.listen((message) { 
    print("接收到来自主线程的反馈消息：$message");
  });
  
}